package com.umerclass.frame.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.umerclass.AppDroid;
import com.umerclass.R;
import com.umerclass.bean.user.UserInfo;
import com.umerclass.db.UserDao;
import com.umerclass.frame.asynctask.TaskExecutor;
import com.umerclass.frame.model.InfoResult;
import com.umerclass.frame.model.MsgBean;
import com.umerclass.frame.okhttp.OkEntityListRequest;
import com.umerclass.frame.okhttp.OkEntityRequest;
import com.umerclass.frame.okhttp.OkHttpTask;
import com.umerclass.frame.okhttp.OkHttpUtils;
import com.umerclass.frame.okhttp.OkSimpleRequest;
import com.umerclass.frame.okhttp.SimpleOkHttpListener;
import com.umerclass.ui.user.UserLoginActivity;
import com.umerclass.utils.MD5Utils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by jack
 *
 */

public abstract class BaseFragment extends Fragment {

    private EventBus eventBus;
    private Toast toast = null;
    private UserDao userDao;
    protected Activity activity;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    InfoResult infoResult = (InfoResult) msg.obj;
                    int state = infoResult.getState();
                    //登录过期
                    if(state == -4){
                        Intent i = new Intent(getActivity(), UserLoginActivity.class);
                        i.putExtra("flag",3);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                        startActivity(i);
                        getActivity().finish();
                    }else{
                        if(infoResult.isSuccess()){
                            int what = infoResult.getTag();
                            if(what == R.id.relogin){
                                UserInfo userInfo = (UserInfo) infoResult.getT();
                                AppDroid.getInstance().setUserInfo(userInfo);
                                userDao.deleteAll();
                                userDao.add(userInfo);
                                loadData();
                            }else {
                                onSuccess(infoResult.getTag(),infoResult);
                            }
                        }else {
                            onFail(infoResult.getTag(),infoResult);
                        }
                    }
                    break;
                default:break;
            }
        }
    };
    //-------------- okhttp -----------//
    public <T> void requestOkhttpEntityList(OkEntityListRequest<T> okEntityListRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(okEntityListRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    public <T> void requestOkhttpEntity(OkEntityRequest<T> okEntityRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(okEntityRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    public <T> void requestOkhttpSimple(OkSimpleRequest<T> tOkSimpleRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(tOkSimpleRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    /**
     * 视图是否已经初初始化
     */
    private View view;

    /**
     * fragment已经关联到activity,这个时候 activity已经传进来了
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
    }

    /**
     * 系统创建fragment的时候回调它，在它里面实例化一些变量
     这些个变量主要是:当你 暂停 停止的时候 你想保持的数据
     如果我们要为fragment启动一个后台线程，可以考虑将代码放于此处
     参数:Bundle savedInstance, 用于保存 Fragment 参数,
     Fragement 也可以 重写 onSaveInstanceState(BundleoutState) 方法, 保存Fragement状态
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private Unbinder unbinder;

    /**
     * 第一次使用的时候 fragment会在这上面画一个layout出来,为了可以画控件 要返回一个 布局的view
     * 当系统用到fragment的时候 fragment就要返回他的view,越快越好,所以尽量在这里不要做耗时操作
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutResId(), container, false);
        bind(view);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化沉浸式
        eventBus = EventBus.getDefault();
        eventBus.register(this);
        userDao = new UserDao(getActivity());
        init();
        loadData();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * 视图销毁的时候讲Fragment是否初始化的状态变为false
     */
    @Override
    public void onDestroyView() {
        if(view!=null){
            ((ViewGroup)view.getParent()).removeView(view);
        }
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelAll();
        if (eventBus != null) {
            eventBus.unregister(this);
        }
        unbinder.unbind();
    }


    public abstract boolean isImmersionBarEnabled();

    /**
     * 返回当前fragment布局文件的id
     *
     * @return
     */
    public abstract int getLayoutResId();

    /**
     * 初始化
     */
    public abstract void init();

    /**
     * 加载网络数据
     */
    public abstract void loadData();

    /**
     * 网络数据返回成功
     */
    protected abstract void onSuccess(int what, InfoResult t);

    /**
     * 网络数据返回失败
     */
    protected abstract void onFail(int what,InfoResult t);

    public EventBus getEventBus() {
        return eventBus;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerMeg(MsgBean msgBean){

    }

    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(AppDroid.getInstance(), msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    /**
     * 跳转到某个Activity
     *
     * @param activity
     * @param targetActivity
     */
    public void switchTo(Activity activity, Class<? extends Activity> targetActivity, boolean finish) {
        switchTo(activity, new Intent(activity, targetActivity),finish);
    }

    public void switchTo(Activity activity, Intent intent, boolean finish) {
        activity.startActivity(intent);
        if(finish){
            getActivity().finish();
        }
        //overridePendingTransition(R.anim.alpha_out, R.anim.alpha_in);
    }

    public void bind(View view){

    }

    public String getMD5(String val) {
        return getString(MD5Utils.getInstance().toMD5(val));
    }

    private String getString(String val) {
        if (!TextUtils.isEmpty(val)) {
            String firstPart = val.substring(0, 2);
            String twoPart = val.substring(2, val.length());
            return twoPart + firstPart;
        }
        return "";
    }

    private Dialog progressDialog;
    private TextView tipTextView;
    public void showProgress(String message) {
        showProgress(message, true);
    }

    public void showProgress(String message, boolean cancelable) {
        if (progressDialog == null) {
            progressDialog = createLoadingDialog(message);
        }
        else if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (!TextUtils.isEmpty(message)) {
            tipTextView.setText(message);
        }
        else {
            tipTextView.setText(getString(R.string.load_text));
        }
        progressDialog.setCancelable(cancelable);
        progressDialog.show();
    }


    /**
     * 得到自定义的progressDialog
     *
     * @param msg
     * @return
     */
    private Dialog createLoadingDialog(String msg) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View v = inflater.inflate(R.layout.dialog_loading,
                null);
        tipTextView = (TextView) v.findViewById(R.id.tipTextView);
        if (!TextUtils.isEmpty(msg)) {
            tipTextView.setText(msg);
        }
        Dialog loadingDialog = new Dialog(getActivity(),
                R.style.loading_dialog);
        loadingDialog.setCancelable(true);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setContentView(v);
        return loadingDialog;
    }

    public void hideProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

}
